<template>
  <div id="EvaluateTaskPage">
    <!-- 默认状态：无任务时显示新建按钮 -->
    <div v-if="!hasTask" class="empty-state">
      <div class="action-wrapper">
        <div class="action-btn" @click="createNewTask">
          <el-icon class="btn-icon"><Plus /></el-icon>
          新建评估任务
        </div>
      </div>
    </div>

    <!-- 有任务时显示完整界面 -->
    <div v-else class="task-content">
      <!-- 评价任务设置区域 -->
      <div class="task-setting-wrapper">
        <div class="header-wrapper">
          <div class="title-wrapper">
            <span class="block-number">1</span>
            <span class="title">任务设置</span>
          </div>
        </div>
        <div class="content-wrapper">
          <!-- 任务基本信息 -->
          <div class="task-setting-item">
            <div class="task-setting-item-title">
              <img src="@/assets/images/icon.png" alt="" />
              <span>任务基本信息</span>
            </div>
            <div class="task-setting-item-content">
              <div class="form-row-wrapper">
                <div class="form-row">
                  <label class="form-label">任务名称</label>
                  <el-input
                    v-model="taskForm.name"
                    placeholder=""
                    class="form-input"
                  />
                </div>
                <div v-if="formErrors.name" class="form-error">
                  {{ formErrors.name }}
                </div>
              </div>
              <div class="form-row-wrapper">
                <div class="form-row">
                  <label class="form-label">任务描述</label>
                  <el-input
                    v-model="taskForm.desc"
                    placeholder=""
                    class="form-input"
                  />
                </div>
                <div v-if="formErrors.desc" class="form-error">
                  {{ formErrors.desc }}
                </div>
              </div>
            </div>
          </div>
          <!-- 评价媒体资源 -->
          <div class="task-setting-item">
            <div class="task-setting-item-title">
              <img src="@/assets/images/icon.png" alt="" />
              <span>评价媒体资源</span>
            </div>
            <div class="task-setting-item-content resource-form">
              <div class="left-form">
                <div class="form-row-wrapper">
                  <div class="form-row">
                    <label class="form-label">区域</label>
                    <el-select
                      v-model="taskForm.areaName"
                      placeholder=""
                      class="form-select"
                      @change="handleAreaChange"
                    >
                      <el-option
                        v-for="(item, index) in areaList"
                        :key="index"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </div>
                  <div v-if="formErrors.areaName" class="form-error">
                    {{ formErrors.areaName }}
                  </div>
                </div>
                <div class="form-row-wrapper">
                  <div class="form-row">
                    <label class="form-label">类型</label>
                    <el-select
                      v-model="taskForm.resourceInfo.resourceType"
                      placeholder=""
                      class="form-select"
                      @change="handleResourceTypeChange"
                    >
                      <el-option
                        v-for="(item, index) in resourceTypeList"
                        :key="index"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </div>
                  <div v-if="formErrors.resourceType" class="form-error">
                    {{ formErrors.resourceType }}
                  </div>
                </div>
                <div class="form-row-wrapper">
                  <div class="form-row">
                    <label class="form-label">节目</label>
                    <el-select
                      v-model="taskForm.resourceInfo"
                      value-key="id"
                      placeholder=""
                      class="form-select"
                      @change="handleResourceChange"
                    >
                      <template
                        v-if="taskForm.resourceInfo.resourceType === '直播'"
                      >
                        <el-option
                          v-for="item in liveResourceList"
                          :key="item.id"
                          :label="item.channelName"
                          :value="item"
                        />
                      </template>
                      <template
                        v-else-if="
                          taskForm.resourceInfo.resourceType === '点播'
                        "
                      >
                        <el-option
                          v-for="item in vodResourceList"
                          :key="item.id"
                          :label="item.programName"
                          :value="item"
                        />
                      </template>
                      <template
                        v-else-if="
                          taskForm.resourceInfo.resourceType === '终端'
                        "
                      >
                        <el-option
                          v-for="item in terminalResourceList"
                          :key="item.id"
                          :label="item.name"
                          :value="item"
                        />
                      </template>
                    </el-select>
                  </div>
                  <div v-if="formErrors.resourceId" class="form-error">
                    {{ formErrors.resourceId }}
                  </div>
                </div>
              </div>
              <div class="right-form">
                <div class="preview-player">
                  <XGPlayer :url="taskForm.resourceInfo.previewUrl" />
                </div>
              </div>
            </div>
          </div>
          <!-- 终端与模板 -->
          <div class="task-setting-item">
            <div class="task-setting-item-title">
              <img src="@/assets/images/icon.png" alt="" />
              <span>终端与模板</span>
            </div>
            <div class="task-setting-item-content template-form">
              <div class="form-row-wrapper">
                <div class="form-row">
                  <label class="form-label">评价模板</label>
                  <el-select
                    v-model="taskForm.templateInfo"
                    placeholder=""
                    class="form-select"
                    value-key="id"
                  >
                    <el-option
                      v-for="item in templateList"
                      :key="item.id"
                      :label="item.name"
                      :value="item"
                    />
                  </el-select>
                </div>
                <div v-if="formErrors.templateId" class="form-error">
                  {{ formErrors.templateId }}
                </div>
              </div>
              <div class="form-row-wrapper">
                <div class="form-row">
                  <label class="form-label">评价专家</label>
                  <el-select
                    v-model="taskForm.expertIds"
                    multiple
                    placeholder=""
                    class="form-select"
                  >
                    <el-option
                      v-for="item in userList"
                      :key="item.id"
                      :label="item.userName"
                      :value="item.id"
                    />
                  </el-select>
                </div>
                <div v-if="formErrors.expertIds" class="form-error">
                  {{ formErrors.expertIds }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 控制区域 -->
      <div class="task-control-wrapper">
        <div class="header-wrapper">
          <div class="title-wrapper">
            <span class="block-number">2</span>
            <span class="title">任务控制</span>
          </div>
        </div>
        <div class="content-wrapper">
          <!-- 评价任务时间控制 -->
          <div class="task-setting-item">
            <div v-if="false" class="task-setting-item-title">
              <img src="@/assets/images/icon.png" alt="" />
              <span>评价任务控制</span>
            </div>
            <div class="task-setting-item-content time-form">
              <div class="form-row-wrapper">
                <div class="form-row">
                  <label class="form-label">评价时长</label>
                  <el-input-number
                    v-model="taskForm.planDuration"
                    :min="1"
                    :max="60"
                    controls-position="right"
                  />（分钟）
                </div>
                <div v-if="formErrors.planDuration" class="form-error">
                  {{ formErrors.planDuration }}
                </div>
              </div>
              <div class="form-row-wrapper">
                <div class="form-row">
                  <label class="form-label">分段时间</label>
                  <el-input-number
                    v-model="taskForm.segmentTime"
                    :min="0"
                    :max="60"
                    controls-position="right"
                  />（分钟）
                </div>
                <div v-if="formErrors.segmentTime" class="form-error">
                  {{ formErrors.segmentTime }}
                </div>
              </div>
            </div>
          </div>
          <!-- 计时 -->
          <div class="task-setting-item countdown-item">
            <div class="task-setting-item-title">
              <img src="@/assets/images/countdown.png" alt="" />
              <span>{{ formatCountdownTime(remainingTime) }}</span>
            </div>
          </div>
          <!-- 控制区 -->
          <div class="task-setting-item control-item">
            <div v-if="false" class="task-setting-item-title">
              <img src="@/assets/images/icon.png" alt="" />
              <span>控制区</span>
            </div>
            <div class="task-setting-item-content control-form">
              <el-button
                class="btn btn-start"
                :class="taskForm.execStatus === 1 ? 'disabled' : ''"
                @click="taskForm.execStatus === 1 ? null : startEvaluation()"
              >
                <el-icon><CaretRight /></el-icon>
                开始评价
              </el-button>
              <el-button
                class="btn btn-pause"
                :class="taskForm.execStatus !== 1 ? 'disabled' : ''"
                @click="taskForm.execStatus !== 1 ? null : pauseEvaluation()"
              >
                <el-icon><VideoPause /></el-icon>
                暂停评价
              </el-button>
              <el-button
                class="btn btn-stop"
                :class="taskForm.execStatus === 3 ? 'disabled' : ''"
                @click="taskForm.execStatus === 3 ? null : stopEvaluation()"
              >
                <el-icon><Close /></el-icon>
                终止评价
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 评价结果区 -->
      <div v-if="taskForm.execStatus" class="task-result-wrapper">
        <div class="header-wrapper">
          <div class="title-wrapper">
            <span class="block-number">3</span>
            <span class="title">任务结果</span>
          </div>
        </div>
        <div class="content-wrapper">
          <div class="tabs-wrapper">
            <div
              class="tab-item"
              :class="currentTab === '' ? 'active' : ''"
              @click="getEvaluateTaskResult()"
            >
              总体评价
            </div>
            <div
              class="tab-item"
              :class="currentTab === item ? 'active' : ''"
              v-for="(item, index) in taskForm.expertIds"
              :key="index"
              @click="getEvaluateTaskResult(item)"
            >
              {{ userListMap.get(item)?.userName }}
            </div>
          </div>
          <div class="result-table">
            <div v-if="currentTab !== ''" class="base-info-wrapper">
              <div class="base-info-item">
                <span>评价人：</span>
                <span>
                  {{ currentTabDataMap["total"]?.evaluatePerson || "--" }}
                </span>
              </div>
              <div class="base-info-item">
                <span>备注：</span>
                <span>
                  {{ currentTabDataMap["total"]?.note || "--" }}
                </span>
              </div>
            </div>
            <el-table
              v-if="currentTab === ''"
              :data="tableQuotaList"
              stripe
              fit
              class="self-stripe-table"
              height="100%"
            >
              <el-table-column type="index" label="序号" width="100">
                <template #default="scope">
                  <div>
                    {{ scope.$index + 1 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="指标" width="200">
                <template #default="scope">
                  <div>
                    {{ scope.row.name }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="平均分" min-width="150">
                <template #default="scope">
                  <div class="average-score">
                    {{
                      getScore(currentTabDataMap[scope.row.id]?.averageScore)
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="中位数" min-width="150">
                <template #default="scope">
                  <div class="average-score">
                    {{ getScore(currentTabDataMap[scope.row.id]?.medianScore) }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="均方差" min-width="150">
                <template #default="scope">
                  <div class="average-score">
                    {{
                      getScore(
                        currentTabDataMap[scope.row.id]?.standardDeviationScore
                      )
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="
                  '权重得分： ' +
                  getScore(currentTabDataMap['total']?.absoluteScore)
                "
                min-width="150"
              >
                <template #default="scope">
                  <div class="total-score">
                    {{
                      getScore(currentTabDataMap[scope.row.id]?.absoluteScore)
                    }}
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <el-table
              v-else
              :data="tableQuotaList"
              stripe
              fit
              class="self-stripe-table"
              height="100%"
            >
              <el-table-column type="index" label="序号" width="100">
                <template #default="scope">
                  <div>
                    {{ scope.$index + 1 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="指标" width="200">
                <template #default="scope">
                  <div>
                    {{ scope.row.name }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(segment, index) in timeSegments"
                :key="segment.label"
                :label="currentTab !== '' ? segment.label : ''"
                min-width="150"
              >
                <template #default="scope">
                  <div
                    class="score-cell"
                    v-if="currentTab !== '' && scoreData[scope.row.id]"
                  >
                    {{ getScore(scoreData[scope.row.id][index]) || "--" }}
                  </div>
                  <div v-else class="score-cell">--</div>
                </template>
              </el-table-column>
              <el-table-column label="平均分" min-width="150">
                <template #default="scope">
                  <div class="average-score">
                    {{
                      getScore(currentTabDataMap[scope.row.id]?.averageScore)
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="
                  '权重得分： ' +
                  getScore(currentTabDataMap['total']?.absoluteScore)
                "
                min-width="150"
              >
                <template #default="scope">
                  <div class="total-score">
                    {{
                      getScore(currentTabDataMap[scope.row.id]?.absoluteScore)
                    }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <!-- 打开评价页面 -->
    <div
      v-if="currentTab !== ''"
      @click="openExpertEvaluateHandle"
      style="
        text-align: right;
        margin-right: 2rem;
        margin-top: 1rem;
        cursor: pointer;
        color: #999;
      "
    >
      打开评价页面
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus, CaretRight, VideoPause, Close } from "@element-plus/icons-vue";
import { formatTime, getScore } from "@/assets/js/utils";
import XGPlayer from "@/components/Player/xgplayer.vue";
import { ListResponseType } from "@/api/globalType";
import { getUserListAPI, UserType } from "@/api/service/user";
import { getTemplateListAPI, TemplateType } from "@/api/service/template";
import {
  addOrUpdateEvaluateTaskAPI,
  updateEvaluateTaskStatusAPI,
  getevaluateTaskListAPI,
  getevaluateTaskDetailAPI,
  EvaluateTaskType,
} from "@/api/service/evaluateTask";

import {
  getEvaluateTaskResultAPI,
  EvaluateTaskResultType,
} from "@/api/service/evaluateTaskResult";
import {
  getLiveResourceListAPI,
  getLiveResourceDetailAPI,
  LiveResourceType,
} from "@/api/service/liveResource";

import {
  getVodResourceListAPI,
  getVodResourceDetailAPI,
  VodResourceType,
} from "@/api/service/vodResource";
import {
  getTerminalResourceListAPI,
  getTerminalResourceDetailAPI,
  TerminalResourceType,
} from "@/api/service/terminalResource";
import { getQuotaListAPI, QuotaType } from "@/api/service/quota";

const router = useRouter();

// 获取全局信息
const instance = getCurrentInstance();
const globalData = instance?.appContext.config.globalProperties.$globalData;
const resourceTypeList = ["直播", "点播", "终端"];
const areaList = ref(globalData.areaList || []);

// 任务状态
const getTaskListTimer = ref<any>(null);

// 倒计时相关
const countdownTimer = ref<any>(null);
const remainingTime = ref<number>(0); // 剩余时间（秒）
const isCountdownRunning = ref<boolean>(false);

const hasTask = ref<boolean | null>(null);
const currentTaskList = ref<EvaluateTaskType[]>([]);
// 获取任务列表
const getTaskList = () => {
  getevaluateTaskListAPI({
    currentPage: 1,
    numPerPage: 1,
  }).then((_data: any) => {
    const data = _data as ListResponseType<EvaluateTaskType>;
    currentTaskList.value = data.list.filter((task) => {
      return task.execStatus < 3;
    });
    if (currentTaskList.value.length > 0) {
      hasTask.value = true;
      taskForm.id = currentTaskList.value[0].id;
      taskForm.name = currentTaskList.value[0].name;
      taskForm.desc = currentTaskList.value[0].desc || "";
      taskForm.resourceInfo.resourceType =
        currentTaskList.value[0]?.resourceType || "";
      taskForm.resourceInfo.id = currentTaskList.value[0]?.resourceId || "";
      taskForm.resourceInfo.name = currentTaskList.value[0]?.resourceName || "";
      taskForm.templateInfo.id = currentTaskList.value[0].templateId;
      taskForm.templateInfo.name = currentTaskList.value[0].templateName;
      taskForm.execStatus = currentTaskList.value[0].execStatus;
      taskForm.planDuration = currentTaskList.value[0].planDuration / 60;
      taskForm.segmentTime = currentTaskList.value[0].segmentTime / 60;
      taskForm.expertIds =
        currentTaskList.value[0]?.expertList?.map((item) => item.id) || [];
      taskForm.realDuration = currentTaskList.value[0].realDuration || 0;
      taskForm.lastStartTime = currentTaskList.value[0].lastStartTime || "";

      getResourceDetail(
        taskForm.resourceInfo.resourceType,
        taskForm.resourceInfo.id
      );
      getQuotaList(taskForm.templateInfo.id);
      getUserList();
      getTemplateList();

      getTaskListTimerHandle();
      // 重置倒计时状态并初始化
      stopCountdown();
      remainingTime.value = calculateRemainingTime();
      initCountdown(); // 初始化倒计时
    }
  });
};
getTaskList();

// 倒计时相关函数
// 计算剩余时间
const calculateRemainingTime = () => {
  const planDurationSeconds = taskForm.planDuration * 60;
  let usedTime = taskForm.realDuration || 0;

  // 如果任务正在进行中，需要加上从lastStartTime到现在的时间
  if (taskForm.execStatus === 1 && taskForm.lastStartTime) {
    const lastStartTime = new Date(taskForm.lastStartTime).getTime();
    const currentTime = Date.now();
    const additionalTime = Math.floor((currentTime - lastStartTime) / 1000);
    usedTime += additionalTime;
  }

  const remaining = planDurationSeconds - usedTime;
  return Math.max(0, remaining);
};

// 格式化时间显示
const formatCountdownTime = (seconds: number) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${hours.toString().padStart(2, "0")}:${minutes
    .toString()
    .padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
};

// 开始倒计时
const startCountdown = () => {
  if (isCountdownRunning.value) {
    return;
  }

  isCountdownRunning.value = true;
  remainingTime.value = calculateRemainingTime();

  countdownTimer.value = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      stopCountdown();
      // 时间到，自动终止评价
      if (taskForm.execStatus === 1) {
        stopEvaluation();
      }
    }
  }, 1000);
};

// 停止倒计时
const stopCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
  isCountdownRunning.value = false;
};

// 初始化倒计时
const initCountdown = () => {
  // 先停止现有的倒计时
  stopCountdown();

  // 如果任务正在进行中，启动倒计时
  if (taskForm.execStatus === 1) {
    startCountdown();
  }
};

// 获取评价任务详情
const getTaskDetail = () => {
  getevaluateTaskDetailAPI({
    evaluateTaskId: taskForm.id,
  }).then((_data: any) => {
    const data = _data as EvaluateTaskType;
    if (data.id === taskForm.id) {
      // 更新任务状态和时间信息
      const oldStatus = taskForm.execStatus;
      taskForm.execStatus = data.execStatus;
      taskForm.realDuration = data.realDuration || 0;
      taskForm.lastStartTime = data.lastStartTime || "";

      // 根据状态变化处理倒计时
      if (oldStatus !== data.execStatus) {
        if (data.execStatus === 1) {
          // 任务开始或重新开始
          startCountdown();
        } else if (data.execStatus === 2) {
          // 任务暂停
          stopCountdown();
        } else if (data.execStatus === 3) {
          // 任务终止
          stopCountdown();
          ElMessage.success("评价已终止");
          clearInterval(getTaskListTimer.value);
          hasTask.value = false;
        }
      }
    }
  });
};

const getTaskListTimerHandle = () => {
  if (getTaskListTimer.value) {
    clearInterval(getTaskListTimer.value);
  }
  getTaskListTimer.value = setInterval(() => {
    getTaskDetail();
  }, 3000);
};
onUnmounted(() => {
  if (getTaskListTimer.value) {
    clearInterval(getTaskListTimer.value);
  }
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});

// 创建新任务
const createNewTask = () => {
  hasTask.value = true;
  // 重置倒计时相关状态
  stopCountdown();
  remainingTime.value = 0;
  isCountdownRunning.value = false;
  getUserList();
  getTemplateList();
};

// 任务表单数据
const taskForm = reactive({
  id: "",
  name: "",
  desc: "",
  areaName: "",
  resourceInfo: {
    id: "",
    resourceType: "",
    name: "",
    previewUrl: "",
  },
  templateInfo: {
    id: "",
    name: "",
  },
  execStatus: 0,
  planDuration: 5,
  segmentTime: 2,
  expertIds: [] as string[],
  createTime: "",
  updateTime: "",
  realDuration: 0, // 已经进行的时长（秒）
  lastStartTime: "", // 最近一次开始的时间点
});

// 获取用户列表
const userList = ref<UserType[]>([]);
const userListMap = ref<Map<string, UserType>>(new Map());
const getUserList = () => {
  getUserListAPI({
    currentPage: 1,
    numPerPage: 1000,
  }).then((_data: any) => {
    const data = _data as ListResponseType<UserType>;
    data.list?.forEach((item) => {
      if (item.userCode === "admin") {
        return;
      }
      userList.value.push(item);
      userListMap.value.set(item.id, item);
    });
  });
};

// 获取模板列表
const templateList = ref<TemplateType[]>([]);
const getTemplateList = () => {
  getTemplateListAPI({
    currentPage: 1,
    numPerPage: 1000,
  }).then((_data: any) => {
    const data = _data as ListResponseType<TemplateType>;
    templateList.value = data.list;
  });
};

// 获取直播资源列表
const liveResourceList = ref<LiveResourceType[]>([]);
const getLiveResourceList = () => {
  getLiveResourceListAPI({
    areaName: taskForm.areaName,
    channelName: "",
    currentPage: 1,
    numPerPage: 1000,
  }).then((_data: any) => {
    const data = _data as ListResponseType<LiveResourceType>;
    liveResourceList.value = data.list;
    const _first = data.list[0];
    taskForm.resourceInfo = {
      id: _first.id,
      resourceType: "直播",
      name: _first.channelName,
      previewUrl: _first.previewUrl || "",
    };
  });
};

// 获取点播资源列表
const vodResourceList = ref<VodResourceType[]>([]);
const getVodResourceList = () => {
  getVodResourceListAPI({
    areaName: taskForm.areaName,
    programName: "",
    currentPage: 1,
    numPerPage: 1000,
  }).then((_data: any) => {
    const data = _data as ListResponseType<VodResourceType>;
    vodResourceList.value = data.list;
    const _first = data.list[0];
    taskForm.resourceInfo = {
      id: _first.id,
      resourceType: "点播",
      name: _first.programName,
      previewUrl: _first.previewUrl || "",
    };
  });
};

// 获取终端资源列表
const terminalResourceList = ref<TerminalResourceType[]>([]);
const getTerminalResourceList = () => {
  getTerminalResourceListAPI({
    areaName: taskForm.areaName,
    name: "",
    currentPage: 1,
    numPerPage: 1000,
  }).then((_data: any) => {
    const data = _data as ListResponseType<TerminalResourceType>;
    terminalResourceList.value = data.list;
    const _first = data.list[0];
    taskForm.resourceInfo = {
      id: _first.id,
      resourceType: "终端",
      name: _first.name,
      previewUrl: _first.previewUrl || "",
    };
  });
};

// 获取资源详情
const getResourceDetail = (type: string, id: string) => {
  if (type === "直播") {
    getLiveResourceList();
    setTimeout(() => {
      getLiveResourceDetail(id);
    }, 1000);
  } else if (type === "点播") {
    getVodResourceList();
    setTimeout(() => {
      getVodResourceDetail(id);
    }, 1000);
  } else if (type === "终端") {
    getTerminalResourceList();
    setTimeout(() => {
      getTerminalResourceDetail(id);
    }, 1000);
  }
};

const getLiveResourceDetail = (id: string) => {
  getLiveResourceDetailAPI({
    liveResourceId: id,
  }).then((_data: any) => {
    const data = _data as LiveResourceType;
    taskForm.areaName = data?.areaName || "";
    taskForm.resourceInfo.previewUrl = data?.previewUrl || "";
  });
};

const getVodResourceDetail = (id: string) => {
  getVodResourceDetailAPI({
    vodResourceId: id,
  }).then((_data: any) => {
    const data = _data as VodResourceType;
    taskForm.areaName = data?.areaName || "";
    taskForm.resourceInfo.previewUrl = data?.previewUrl || "";
  });
};

const getTerminalResourceDetail = (id: string) => {
  getTerminalResourceDetailAPI({
    terminalResourceId: id,
  }).then((_data: any) => {
    const data = _data as TerminalResourceType;
    taskForm.areaName = data?.areaName || "";
    taskForm.resourceInfo.previewUrl = data?.previewUrl || "";
  });
};

// 区域选择变化
const handleAreaChange = (value: any) => {
  taskForm.areaName = value;
  taskForm.resourceInfo.id = "";
  taskForm.resourceInfo.previewUrl = "";
  taskForm.resourceInfo.name = "";
  if (taskForm.resourceInfo.resourceType === "直播") {
    getLiveResourceList();
  } else if (taskForm.resourceInfo.resourceType === "点播") {
    getVodResourceList();
  } else if (taskForm.resourceInfo.resourceType === "终端") {
    getTerminalResourceList();
  }
};

// 资源类型选择变化
const handleResourceTypeChange = (value: any) => {
  taskForm.resourceInfo.resourceType = value;
  taskForm.resourceInfo.id = "";
  taskForm.resourceInfo.name = "";
  taskForm.resourceInfo.previewUrl = "";
  if (value === "直播") {
    getLiveResourceList();
  } else if (value === "点播") {
    getVodResourceList();
  } else if (value === "终端") {
    getTerminalResourceList();
  }
};

// 资源选择变化
const handleResourceChange = (value: any) => {
  taskForm.resourceInfo.id = value.id;
  taskForm.resourceInfo.name = value.name;
  taskForm.resourceInfo.previewUrl = value.previewUrl;
};

// 表单错误信息
const formErrors = reactive({
  name: "",
  desc: "",
  areaName: "",
  resourceType: "",
  resourceId: "",
  templateId: "",
  expertIds: "",
  planDuration: "",
  segmentTime: "",
});

// 清空所有错误信息
const clearFormErrors = () => {
  Object.keys(formErrors).forEach((key) => {
    (formErrors as any)[key] = "";
  });
};

// 表单校验方法
const validateTaskForm = () => {
  // 先清空之前的错误信息
  clearFormErrors();

  let hasError = false;

  // 校验任务名称
  if (!taskForm.name || taskForm.name.trim() === "") {
    formErrors.name = "任务名称不能为空";
    hasError = true;
  }

  // 校验任务描述
  if (!taskForm.desc || taskForm.desc.trim() === "") {
    formErrors.desc = "任务描述不能为空";
    hasError = true;
  }

  // 校验区域
  if (!taskForm.areaName || taskForm.areaName.trim() === "") {
    formErrors.areaName = "区域不能为空";
    hasError = true;
  }

  // 校验资源类型
  if (
    !taskForm.resourceInfo.resourceType ||
    taskForm.resourceInfo.resourceType.trim() === ""
  ) {
    formErrors.resourceType = "资源类型不能为空";
    hasError = true;
  }

  // 校验节目资源
  if (!taskForm.resourceInfo.id || taskForm.resourceInfo.id.trim() === "") {
    formErrors.resourceId = "节目资源不能为空";
    hasError = true;
  }

  // 校验评价模板
  if (!taskForm.templateInfo.id || taskForm.templateInfo.id.trim() === "") {
    formErrors.templateId = "评价模板不能为空";
    hasError = true;
  }

  // 校验评价终端
  if (!taskForm.expertIds || taskForm.expertIds.length === 0) {
    formErrors.expertIds = "评价终端不能为空，至少选择一个终端";
    hasError = true;
  }

  // 校验评价时长
  if (!taskForm.planDuration || taskForm.planDuration <= 0) {
    formErrors.planDuration = "评价时长必须大于0分钟";
    hasError = true;
  }

  // 校验分段时间
  if (taskForm.segmentTime < 0) {
    formErrors.segmentTime = "分段时间不能为负数";
    hasError = true;
  } else if (
    taskForm.segmentTime > 0 &&
    taskForm.segmentTime >= taskForm.planDuration
  ) {
    formErrors.segmentTime = "分段时间不能大于或等于评价时长";
    hasError = true;
  }

  return !hasError;
};

// 评价控制方法
const startEvaluationLoading = ref(false);
const startEvaluation = () => {
  if (startEvaluationLoading.value) {
    return;
  }

  // 执行表单校验
  const isValid = validateTaskForm();
  if (!isValid) {
    return;
  }

  startEvaluationLoading.value = true;
  addOrUpdateEvaluateTaskAPI({
    id: taskForm.id,
    name: taskForm.name,
    desc: taskForm.desc,
    resourceType: taskForm.resourceInfo.resourceType,
    resourceId: taskForm.resourceInfo.id,
    resourceName: taskForm.resourceInfo.name,
    templateId: taskForm.templateInfo.id,
    templateName: taskForm.templateInfo.name,
    execStatus: 1, // 0-未开始 1-进行中 2-暂停中 3-已结束
    planDuration: taskForm.planDuration * 60,
    segmentTime: taskForm.segmentTime * 60,
    expertIds: taskForm.expertIds,
  })
    .then((_data: any) => {
      ElMessage.success("评价已开始");
      taskForm.id = _data;
      taskForm.execStatus = 1;
      taskForm.lastStartTime = formatTime(new Date()); // 记录开始时间

      // 显示评价结果
      if (!quotaList.value.length) {
        getQuotaList(taskForm.templateInfo.id);
      }

      getTaskListTimerHandle();
      startCountdown(); // 启动倒计时
    })
    .catch((err) => {
      ElMessage.error("开始评价任务失败");
    })
    .finally(() => {
      startEvaluationLoading.value = false;
    });
};

const pauseEvaluationLoading = ref(false);
const pauseEvaluation = () => {
  if (pauseEvaluationLoading.value) {
    return;
  }
  pauseEvaluationLoading.value = true;
  updateEvaluateTaskStatusAPI({
    evaluateTaskId: taskForm.id,
    time: formatTime(new Date()),
    execStatus: 2,
  })
    .then(() => {
      ElMessage.success("评价已暂停");
      taskForm.execStatus = 2;
      stopCountdown(); // 暂停倒计时
    })
    .catch((err) => {
      ElMessage.error("暂停评价任务失败");
    })
    .finally(() => {
      pauseEvaluationLoading.value = false;
    });
};

const stopEvaluationLoading = ref(false);
const stopEvaluation = () => {
  if (stopEvaluationLoading.value) {
    return;
  }
  stopEvaluationLoading.value = true;
  updateEvaluateTaskStatusAPI({
    evaluateTaskId: taskForm.id,
    time: formatTime(new Date()),
    execStatus: 3,
  })
    .then(() => {
      ElMessage.success("评价已终止");
      taskForm.execStatus = 3;
      stopCountdown(); // 停止倒计时
    })
    .catch((err) => {
      ElMessage.error("终止评价任务失败");
    })
    .finally(() => {
      stopEvaluationLoading.value = false;
    });
};

// 获取评价任务结果
const currentTabDataMap = ref<
  Record<
    string,
    {
      averageScore: number;
      absoluteScore: number;
      medianScore: number;
      standardDeviationScore: number;
      evaluatePerson: string;
      note: string;
    }
  >
>({});
const currentTab = ref<string>("");
const timeSegments = ref<Array<{ label: string; duration: number }>>([]);
const scoreData = ref<Record<string, Record<string, number>>>({});

// 获取当前模板指标列表
const quotaList = ref<QuotaType[]>([]);
const tableQuotaList = ref<any[]>([]);
const getQuotaList = (templateId: string) => {
  getQuotaListAPI({
    templateId,
  }).then((_data: any) => {
    const data = _data as QuotaType[];
    quotaList.value = data;
    tableQuotaList.value = data;

    // 计算打分分段
    calculateTimeSegments(
      taskForm.planDuration * 60,
      taskForm.segmentTime * 60
    );
    initializeScoreData();
    getEvaluateTaskResult();
  });
};

const getEvaluateTaskResult = (expertId?: string) => {
  getEvaluateTaskResultAPI({
    evaluateTaskId: taskForm.id,
    expertId,
  })
    .then((_data: any) => {
      const data = _data as EvaluateTaskResultType[];
      currentTab.value = expertId || "";
      if (Array.isArray(data) && data.length > 0) {
        // 创建新的评分数据对象，确保响应式更新
        const newScoreData: Record<
          string,
          {
            averageScore: number;
            absoluteScore: number;
            medianScore: number;
            standardDeviationScore: number;
            evaluatePerson: string;
            note: string;
          }
        > = {};
        data?.forEach((item) => {
          if (item.isTotalScore === true) {
            newScoreData["total"] = {
              averageScore: item.averageScore || 0,
              absoluteScore: item.absoluteScore || 0,
              medianScore: item.medianScore || 0,
              standardDeviationScore: item.standardDeviationScore || 0,
              evaluatePerson: item.evaluatePerson || "",
              note: item.note || "",
            };
          } else {
            newScoreData[item.quotaId] = {
              averageScore: item.averageScore || 0,
              absoluteScore: item.absoluteScore || 0,
              medianScore: item.medianScore || 0,
              standardDeviationScore: item.standardDeviationScore || 0,
              evaluatePerson: "",
              note: "",
            };
          }
        });
        // 替换整个对象以触发Vue响应式更新
        currentTabDataMap.value = newScoreData;

        // 解析已有的评价结果并回显到界面
        parseAndFillExistingResults(data);
      } else {
        currentTabDataMap.value = {};
        scoreData.value = {};
      }
    })
    .catch((err) => {
      ElMessage.error("获取评价任务结果失败");
    });
};

// 初始化评分数据结构
const initializeScoreData = () => {
  quotaList.value.forEach((quota) => {
    if (quota.id) {
      const quotaId = quota.id;
      // 如果该指标还没有数据，则初始化
      if (!scoreData.value[quotaId]) {
        scoreData.value[quotaId] = {};
      }

      // 为每个时间段初始化分数（如果还没有分数的话）
      timeSegments.value.forEach((segment, index) => {
        if (scoreData.value[quotaId][index] === undefined) {
          scoreData.value[quotaId][index] = 0;
        }
      });
    }
  });
};

// 计算时间分段
const calculateTimeSegments = (planDuration: number, segmentTime: number) => {
  const segments: Array<{ label: string; duration: number }> = [];
  let currentTime = 0;

  while (currentTime < planDuration) {
    const remainingTime = planDuration - currentTime;

    // 如果剩余时间不足一个完整分段，且已经有分段存在，则合并到最后一个分段
    if (remainingTime < segmentTime && segments.length > 0) {
      // 将剩余时间合并到最后一个分段，累计时间为总时长
      segments[segments.length - 1].duration = planDuration;
      segments[segments.length - 1].label = `${(planDuration / 60).toFixed(
        0
      )}分钟得分`;
      break;
    }

    const nextTime = currentTime + segmentTime;
    segments.push({
      label: `${(nextTime / 60).toFixed(0)}分钟得分`,
      duration: nextTime,
    });

    currentTime = nextTime;
  }
  timeSegments.value = segments;
};

// 解析并填充已有的评价结果
const parseAndFillExistingResults = (results: EvaluateTaskResultType[]) => {
  results.forEach((result) => {
    if (result.quotaId && result.segmentScore) {
      try {
        // 解析 segmentScore 格式 "{1:7,2:8}"
        const segmentScores = JSON.parse(
          result.segmentScore.replace(/(\w+):/g, '"$1":')
        );

        // 将分数填入 scoreData
        if (!scoreData.value[result.quotaId]) {
          scoreData.value[result.quotaId] = {};
        }

        Object.keys(segmentScores).forEach((segmentIndex) => {
          const index = parseInt(segmentIndex) - 1; // 转换为从0开始的索引
          if (index >= 0 && index < timeSegments.value.length) {
            scoreData.value[result.quotaId][index] =
              segmentScores[segmentIndex];
          }
        });
      } catch (error) {
        console.error("解析分段分数失败：", error);
      }
    }
  });
};

// 打开评价页面
const openExpertEvaluateHandle = () => {
  const routeData = router.resolve({
    name: "ExpertEvaluate",
    query: {
      taskId: taskForm.id,
      templateId: taskForm.templateInfo.id,
      expertId: currentTab.value,
    },
  });
  window.open(routeData.href, "_blank");
};
</script>

<style scoped lang="scss">
#EvaluateTaskPage {
  height: 100%;
  overflow: auto;
  padding: 2rem 0;
  background-color: #fff;
}

.empty-state {
  .action-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 2rem;
    padding: 3rem;
    margin-bottom: 1rem;
    background-color: $text-color-placeholder;
    border-radius: 0.5rem;
    border: 1px solid $border-color-brand;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .action-btn {
      display: flex;
      align-items: center;
      padding: 0.5rem 1.5rem;
      background-color: $color_brand;
      color: #fff;
      border-radius: 0.5rem;
      cursor: pointer;
      font-size: $font-size-block-title;
      transition: all 0.3s;

      .btn-icon {
        margin-right: 0.5rem;
      }

      &:hover:not(.disabled) {
        background-color: darken($color_brand, 10%);
      }

      &.disabled {
        opacity: 0.6;
        cursor: not-allowed;
        pointer-events: none;
      }
    }
  }
}
.task-content {
  .header-wrapper {
    .title-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      min-height: 2rem;
      padding-left: 2rem;
      color: $color_brand;
      font-size: $font-size-block-title;
    }
    .title-wrapper::before {
      position: absolute;
      left: 0;
      top: 50%;
      display: block;
      content: "";
      width: 3px;
      height: 1.8rem;
      background-color: $color_brand;
      transform: translateY(-50%);
    }
    .block-number {
      margin-right: 1rem;
      width: 2rem;
      height: 2rem;
      display: flex;
      align-items: baseline;
      justify-content: center;
      font-size: $font-size-base-btn-text;
      color: #fff;
      background-color: $color_brand;
      border-radius: 50%;
    }
  }
  .content-wrapper {
    padding: 2rem 2rem;
  }
}
.task-setting-wrapper {
  .content-wrapper {
    margin: 1rem 2rem;
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
    gap: 2rem;
    border: 1px solid $border-color-brand;
    border-radius: 0.5rem;
    background-color: rgba($color_brand, 0.03);
  }
  .task-setting-item {
    padding-right: 2rem;
    border-right: 1px solid $border-color-brand;
    .task-setting-item-title {
      display: flex;
      align-items: center;
      font-size: $font-size-block-title;
      color: $text-color-primary;
      img {
        margin-right: 1.5rem;
      }
    }
  }
  .task-setting-item:last-child {
    border-right: none;
  }
  .form-row {
    display: flex;
    align-items: center;
    margin-top: 2rem;
    padding-left: 3.5rem;

    .form-label {
      width: 8rem;
      color: $text-color-regular;
      font-size: $font-size-base;
    }

    .form-input,
    .form-select {
      flex: 1;
    }
  }
  .resource-form {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .left-form {
      flex: 1;
      margin-right: 3rem;
    }
    .right-form {
      width: 241.7px;
    }

    .form-label {
      width: 6rem;
      color: $text-color-regular;
      font-size: $font-size-base;
    }
  }
  .template-form {
    display: flex;
    flex-direction: column;
    .form-row-wrapper {
      width: 100%;
    }
  }
  .preview-player {
    margin-top: 2rem;
    height: 136px;
  }
}
.task-control-wrapper {
  margin-top: 2rem;
  .title-wrapper {
    color: #ff7e00 !important;
  }
  .title-wrapper::before {
    background-color: #ff7e00 !important;
  }
  .block-number {
    background-color: #ff7e00 !important;
  }
  .content-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 1rem 2rem;
    padding: 2rem 2rem;
    border: 1px solid #ff7e00;
    border-radius: 0.5rem;
    background-color: rgba(#ff7e00, 0.03);
  }
  .time-form {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    width: 100%;
    color: $text-color-regular;
    .form-row-wrapper {
      margin-top: 2rem;
    }
    .form-row-wrapper:nth-child(1) {
      margin-top: 0;
    }

    .form-row {
      display: flex;
      align-items: center;
      padding-left: 3.5rem;
      width: 100%;

      .form-label {
        width: 8rem;
        color: $text-color-regular;
        font-size: $font-size-base;
      }

      .form-input,
      .form-select {
        flex: 1;
      }
      .el-input-number {
        width: 20rem;
      }
    }
  }
  .countdown-item {
    font-size: 4rem;
    color: #ff7e00;
    .task-setting-item-title {
      display: flex;
      align-items: center;
      img {
        padding-right: 1rem;
      }
    }
  }
  .control-item {
    width: 50%;
  }
  .control-form {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: center;

    .btn {
      flex: 1;
      display: flex;
      align-items: center;
      margin-right: 3rem;
      padding: 1.8rem 1.5rem;
      font-size: $font-size-block-title;
      background: $color_brand;
      color: white;
      border: none;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        background-color: darken($color_brand, 10%);
      }
      &:last-child {
        margin-right: 0;
      }
      &.disabled {
        background-color: $text-color-disabled;
        cursor: not-allowed;
        pointer-events: none;
      }
    }
  }
}
.task-result-wrapper {
  position: relative;
  margin-top: 2rem;
  .title-wrapper {
    color: #09c987 !important;
  }
  .title-wrapper::before {
    background-color: #09c987 !important;
  }
  .block-number {
    background-color: #09c987 !important;
  }
  .content-wrapper {
    margin: 1rem 2rem;
    padding: 2rem 2rem;
    border: 1px solid #09c987;
    border-radius: 0.5rem;
    background-color: rgba(#09c987, 0.03);
  }
  .tabs-wrapper {
    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
    border: 1px solid $color_brand;
    border-radius: 0.5rem;
    .tab-item {
      display: inline-flex;
      padding: 0.5rem 1.5rem;
      background-color: #fff;
      font-size: $font-size-base;
      color: $text-color-regular;
      border-right: 1px solid $border-color-brand;
      cursor: pointer;
      &:last-child {
        border-right: none;
      }
      &:hover {
        background-color: $color_brand;
        color: #fff;
      }
      &.active {
        background-color: $color_brand;
        color: #fff;
      }
    }
  }
  .self-stripe-table {
    margin-top: 1.5rem;
    .total-score {
      font-size: $font-size-base;
      color: $color_brand;
    }
  }
  .base-info-wrapper {
    margin-top: 1rem;
    padding: 1rem 1rem 1rem 0;
    border: 1px solid $border-color-brand;
    border-radius: 0.5rem;
    font-size: $font-size-base;
    color: $color_brand;
    .base-info-item {
      display: flex;
      align-items: center;
      margin-bottom: 0.5rem;
      span:first-child {
        width: 10rem;
        text-align: right;
      }
    }
    span:last-child {
      margin-left: 0.5rem;
    }
  }
}

// 表单错误信息样式
.form-error {
  margin-top: 0.5rem;
  margin-left: 8rem;
  padding-left: 3.5rem;
  font-size: 1.2rem;
  color: #f56c6c;
  line-height: 1.2;
}

// 媒体资源表单中的错误信息样式
.resource-form .form-error {
  margin-left: 6rem;
}

// 响应式适配
@media (max-width: $breakpoint-lg) {
  .task-setting-item {
    width: 100% !important;
  }

  .form-error {
    margin-left: 0;
    padding-left: 0;
  }

  .resource-form .form-error {
    margin-left: 0;
  }
}
</style>
